package com.jhhc.WaterQuality.Calculate.Forecast;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jhhc.FloodForecast.Sensor.Pojo.BDMS_ST_SENSOR_B;
import com.jhhc.FloodForecast.Sensor.Service.BDMS_ST_SENSOR_BService;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.GZABO.Result;
import com.jhhc.WaterQuality.BaseInfo.entity.BDMS_BA_BASINSCHEME_B;
import com.jhhc.WaterQuality.BaseInfo.entity.BDMS_YB_FORECASTSTATION_B;
import com.jhhc.WaterQuality.BaseInfo.service.BDMS_BA_BASINSCHEME_BService;
import com.jhhc.WaterQuality.BaseInfo.service.BDMS_YB_FORECASTSCHEME_BService;
import com.jhhc.WaterQuality.BaseInfo.service.BDMS_YB_FORECASTSTATION_BService;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.BDMS_CALCULATESCHEME_M;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.BDMS_SLX_RESULT_M;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.BDMS_WQ_RESULT_M;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.WQ_AWQMD_D;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.param.ElementParam;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.param.ModifyParam;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.result.*;

import com.jhhc.RHDB.Data.Pojo.Data;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.param.GetCalSchemeInfoParam;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.param.RunParam;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.result.CalSchemeInfo;
//import com.jhhc.WaterQuality.Calculate.Forecast.service.BDMS_CALCULATESCHEME_MService;
import com.jhhc.WaterQuality.Calculate.Forecast.entity.result.RunResult;
import com.jhhc.WaterQuality.Calculate.Forecast.service.BDMS_CALCULATESCHEME_MService;
import com.jhhc.WaterQuality.Calculate.Forecast.service.BDMS_SLX_RESULT_MService;
import com.jhhc.WaterQuality.Calculate.Forecast.service.BDMS_WQ_RESULT_MService;
import com.jhhc.WaterQuality.Calculate.Forecast.service.WQ_AWQMD_DService;
import com.jhhc.WaterQuality.Calculate.Forecast.util.AsyncUtil;
import com.jhhc.utils.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Api(value="WaterQualityBaseInfoController",tags={"预报计算服务"})
@RequestMapping(value = "WaterQuality/Calculate/Forecast",headers = "Accept=application/json")
@RestController("WaterQualityCalculateController")
public class CalculateController {

    @Autowired
    private BDMS_CALCULATESCHEME_MService bdms_calculatescheme_mService;
    @Autowired
    private BDMS_YB_FORECASTSCHEME_BService bdms_yb_forecastscheme_bService;
    @Autowired
    private BDMS_SLX_RESULT_MService bdms_slx_result_mService;
    @Autowired
    private BDMS_BA_BASINSCHEME_BService bdms_ba_basinscheme_bService;
    @Autowired
    private BDMS_YB_FORECASTSTATION_BService bdms_yb_forecaststation_bService;
    @Autowired
    private BDMS_ST_SENSOR_BService bdms_st_sensor_bService;
    @Autowired
    private BDMS_WQ_RESULT_MService bdmsWqResultMService;
    @Autowired
    private WQ_AWQMD_DService wq_awqmd_dService;
    @Autowired
    private AsyncUtil asyncUtil;
    //Run
    @Value("${address}")
    String address;
    @Value("${stationCodes}")
    String stationInfos;
    @Value("${modelPath}")
    String  modelPath;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar calendar = new GregorianCalendar();


    @ApiOperation("RRRRRRR")
    @RequestMapping(value = "rrrr", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult RRRRRRRR(@RequestBody RunParam runParam) throws Exception {
        JsonResult jsonResult = new JsonResult();
        runParam.setFlag(false);

        // System.out.println(runParam.getCalSchemeId());
        String cal =  runParam.getCalSchemeId();
        List<String> calIds =new ArrayList<>();
        calIds.add(cal);
//        boolean forecastModel = runParam.isForecastModel();
        boolean forecastModel = true;
        String elemntId =null;
//        if (runParam.getElementId()!=null&& !"".equals(runParam.getElementId())) {
//            elemntId = runParam.getElementId();
//        }
        //计算结方案入库
        BDMS_CALCULATESCHEME_M bdms_calculatescheme_m= new BDMS_CALCULATESCHEME_M();
        bdms_calculatescheme_m.setCschemeid(runParam.getCalSchemeId());
        bdms_calculatescheme_m.setDtmforecast(runParam.getForecastTime());
        //bdms_calculatescheme_m.setCalinterval(runParam.getCalTimeSpan());
        bdms_calculatescheme_m.setDtmstart(runParam.getForecastBeginTime());
        bdms_calculatescheme_m.setFschemeid(runParam.getForecastSchemeId());
        calendar.setTime(format.parse(runParam.getForecastTime()));
        calendar.add(Calendar.HOUR,runParam.getCalTimeSpan());
        bdms_calculatescheme_m.setDtmend(format.format(calendar.getTime()));
        bdms_calculatescheme_m.setPid(runParam.getProjectId());
        bdms_calculatescheme_m.setDtmcalculate(format.format(new Date()));
        bdms_calculatescheme_m.setTag(String.valueOf(forecastModel));
        bdms_calculatescheme_m.setUserid(runParam.getUserId());
        System.out.println("yubaojieshushijian"+bdms_calculatescheme_m.getDtmend());
        //根据计算方案id获取计算方案信息
        BDMS_CALCULATESCHEME_M bdmsCalculateschemeM = bdms_calculatescheme_mService.seletcById(cal);
        System.out.println("bdmsCalculateschemeM"+bdmsCalculateschemeM);
        List<String> stcds = new ArrayList<>();
        if (bdmsCalculateschemeM==null) {

            asyncUtil.readFile("", "", bdms_calculatescheme_m, "1101", 327928);


        }
        return  jsonResult;
    }
    public static List<String> splitStringIntoEightLengthSegments(String inputString) {
        List<String> segments = new ArrayList<>();

        int length = inputString.length();
        for (int i = 0; i < length; i += 8) {
            int endIndex = Math.min(i + 8, length);
            String segment = inputString.substring(i, endIndex);
            segments.add(segment);
        }

        return segments;
    }
    @ApiOperation("EFDC水质预报数据预报计算")
    @RequestMapping(value = "Run", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult runByEFDC(@RequestBody RunParam runParam) throws Exception {
        JsonResult jsonResult = new JsonResult();


        // System.out.println(runParam.getCalSchemeId());
        String cal =  runParam.getCalSchemeId();
        List<String> calIds =new ArrayList<>();
        calIds.add(cal);
        boolean forecastModel  = runParam.isForecastModel();;



        System.out.println(forecastModel);
        String elemntId =null;
//        if (runParam.getElementId()!=null&& !"".equals(runParam.getElementId())) {
//            elemntId = runParam.getElementId();
//        }
        if (runParam.getProjectId()==240211){
            runParam.setFlag(false);
        }
        //计算结方案入库
        BDMS_CALCULATESCHEME_M bdms_calculatescheme_m= new BDMS_CALCULATESCHEME_M();
        bdms_calculatescheme_m.setCschemeid(runParam.getCalSchemeId());
        bdms_calculatescheme_m.setCschemenm(runParam.getForecastName());
        bdms_calculatescheme_m.setDtmforecast(runParam.getForecastTime());
        //bdms_calculatescheme_m.setCalinterval(runParam.getCalTimeSpan());
        bdms_calculatescheme_m.setDtmstart(runParam.getForecastBeginTime());
        bdms_calculatescheme_m.setFschemeid(runParam.getForecastSchemeId());
        calendar.setTime(format.parse(runParam.getForecastTime()));
        calendar.add(Calendar.HOUR,runParam.getCalTimeSpan());
        bdms_calculatescheme_m.setDtmend(format.format(calendar.getTime()));
        bdms_calculatescheme_m.setPid(runParam.getProjectId());
        bdms_calculatescheme_m.setDtmcalculate(format.format(new Date()));
        bdms_calculatescheme_m.setTag(String.valueOf(forecastModel));
        bdms_calculatescheme_m.setUserid(runParam.getUserId());
        System.out.println("yubaojieshushijian"+bdms_calculatescheme_m.getDtmend());
        //根据计算方案id获取计算方案信息
        BDMS_CALCULATESCHEME_M bdmsCalculateschemeM = bdms_calculatescheme_mService.seletcById(cal);
        System.out.println("bdmsCalculateschemeM"+bdmsCalculateschemeM);
        List<String> stcds = new ArrayList<>();
        if (bdmsCalculateschemeM==null){
            if (runParam.isFlag()){
                Date date1 = format.parse(bdms_calculatescheme_m.getDtmforecast());
                Date date2 = format.parse(bdms_calculatescheme_m.getDtmend());
                Date date3 = format.parse(bdms_calculatescheme_m.getDtmstart());
                // 计算时间差（以分钟为单位）  // 计算时间差（以小时为单位）
                //            long difference = (date2.getTime() - date1.getTime()) / (1000 * 60 * 60);
                //总预报时间
                int hour1 = Integer.parseInt(String.valueOf( (date2.getTime() - date3.getTime()) / (1000 * 60 * 60)));
                //边界段
                int hour = Integer.parseInt(String.valueOf( (date2.getTime() - date1.getTime()) / (1000 * 60 * 60)));
                //模拟段
                int hour2 = Integer.parseInt(String.valueOf( (date1.getTime() - date3.getTime()) / (1000 * 60 * 60)));
                String [] sensors ;
                if (runParam.getProjectId()==2107){
                    sensors= new String[]{"1101","1103","1105"};
                }else {
                    sensors = new String[]{"1101", "1102", "1103", "1104", "1105"};
                }
                System.out.println("sensors"+Arrays.toString(sensors));
                //
                int dp =2;
                int i=0;
                for (String sen:sensors){
                    boolean modify = false;
                    String values1 = sen;
                    String vk = null;
                    StringBuilder vks = new StringBuilder();
                    switch (sen){
                        case "1101":
                            sen="TN";
                            vk ="2.0000";
                            break;
                        case "1102":
                            sen="TP";
                            vk ="0.2000";
                            break;
                        case "1103":
                            sen="cod";
                            vk ="15.0000";
                            break;
                        case "1104":
                            sen="SY";
                            vk ="0.0000";
                            break;
                        case "1105":
                            vk ="0.3000";
                            sen="NH4";
                            break;
                        default:
                            break;
                    }
                    StringBuilder sy = new StringBuilder();
                    //生成模拟段数据
                    BDMS_BA_BASINSCHEME_B bdmsBaBasinschemeB = bdms_ba_basinscheme_bService.queryById(runParam.getProjectId()).get(0);
                    String stcd = bdmsBaBasinschemeB.getUpb().split(",")[1];
                    stcds.add(stcd);
                    //判断库里是否有实测数据作为模拟段区间
                    List<WQ_AWQMD_D> wq_awqmd_ds = wq_awqmd_dService.queryAllByStcds(stcds, bdms_calculatescheme_m.getDtmstart(), bdms_calculatescheme_m.getDtmforecast());
                    //System.out.println("moniduanchaku"+wq_awqmd_ds);
                    if (!wq_awqmd_ds.isEmpty()) {
                        for (WQ_AWQMD_D wq_awqmd_d : wq_awqmd_ds) {
                            //根据 去到的数据减去模拟开始时间来生产文件
                            switch (sen) {
                                case "cod":
                                    if (wq_awqmd_ds.size()==hour+1){
                                        //化学需氧量
                                        if (wq_awqmd_d.getCodcr() != null) {
                                            vks.append("     ").append(Integer.parseInt(String.valueOf((format.parse(wq_awqmd_d.getSpt()).getTime() - date3.getTime()) / (1000 * 60 * 60))))
                                                    .append(".000    ").append(wq_awqmd_d.getCodcr()).append("\n");
                                        } else {
                                            vks.append("     ").append(Integer.parseInt(String.valueOf((format.parse(wq_awqmd_d.getSpt()).getTime() - date3.getTime()) / (1000 * 60 * 60))))
                                                    .append(".000    ").append("15.0000").append("\n");
                                        }
                                    }else {
                                        for (int i1=0 ;i1<hour2+1;i1++){
                                            vks.append("     ").append(i1)
                                                    .append(".000    ").append("15.0000").append("\n");
                                        }
                                    }

                                    break;
                                case "TN":
                                    // 总氮
                                    if (wq_awqmd_ds.size()==hour+1){
                                        //化学需氧量
                                        if (wq_awqmd_d.getCodcr() != null) {
                                            vks.append("     ").append(Integer.parseInt(String.valueOf((format.parse(wq_awqmd_d.getSpt()).getTime() - date3.getTime()) / (1000 * 60 * 60))))
                                                    .append(".000    ").append(wq_awqmd_d.getTn()).append("\n");
                                        } else {
                                            vks.append("     ").append(Integer.parseInt(String.valueOf((format.parse(wq_awqmd_d.getSpt()).getTime() - date3.getTime()) / (1000 * 60 * 60))))
                                                    .append(".000    ").append("2.0000").append("\n");
                                        }
                                    }else {
                                        for (int i1=0 ;i1<hour2+1;i1++){
                                            vks.append("     ").append(i1)
                                                    .append(".000    ").append("2.0000").append("\n");
                                        }
                                    }
                                    break;
                                case "TP":
                                    // 总磷
                                    if (wq_awqmd_ds.size()==hour+1){
                                        //化学需氧量
                                        if (wq_awqmd_d.getCodcr() != null) {
                                            vks.append("     ").append(Integer.parseInt(String.valueOf((format.parse(wq_awqmd_d.getSpt()).getTime() - date3.getTime()) / (1000 * 60 * 60))))
                                                    .append(".000    ").append(wq_awqmd_d.getTp()).append("\n");
                                        } else {
                                            vks.append("     ").append(Integer.parseInt(String.valueOf((format.parse(wq_awqmd_d.getSpt()).getTime() - date3.getTime()) / (1000 * 60 * 60))))
                                                    .append(".000    ").append("0.2000").append("\n");
                                        }
                                    }else {
                                        for (int i1=0 ;i1<hour2+1;i1++){
                                            vks.append("     ").append(i1)
                                                    .append(".000    ").append("0.2000").append("\n");
                                        }
                                    }
                                    break;
                                case "NH4":
                                    if (wq_awqmd_ds.size()==hour+1){
                                        //化学需氧量
                                        if (wq_awqmd_d.getCodcr() != null) {
                                            vks.append("     ").append(Integer.parseInt(String.valueOf((format.parse(wq_awqmd_d.getSpt()).getTime() - date3.getTime()) / (1000 * 60 * 60))))
                                                    .append(".000    ").append(wq_awqmd_d.getNh3n()).append("\n");
                                        } else {
                                            vks.append("     ").append(Integer.parseInt(String.valueOf((format.parse(wq_awqmd_d.getSpt()).getTime() - date3.getTime()) / (1000 * 60 * 60))))
                                                    .append(".000    ").append("0.3000").append("\n");
                                        }
                                    }else {
                                        for (int i1=0 ;i1<hour2+1;i1++){
                                            vks.append("     ").append(i1)
                                                    .append(".000    ").append("0.3000").append("\n");
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    } else {
                        for (int h = 0; h <= hour2; h++) {
                            if ("cod".equals(sen)) {
                                vks.append("     ").append(h)
                                        .append(".000    ").append("15.0000").append("\n");
                            } else if ("TN".equals(sen)){
                                vks.append("     ").append(h)
                                        .append(".000    ").append("2.0000").append("\n");
                            } else if ("TP".equals(sen)) {
                                vks.append("     ").append(h)
                                        .append(".000    ").append("0.2000").append("\n");
                            } else if ("NH4".equals(sen)) {
                                vks.append("     ").append(h)
                                        .append(".000    ").append("0.3000").append("\n");
                            }
                        }
                    }
                    StringBuilder pser = new StringBuilder();
                    StringBuilder qser = new StringBuilder();
                    //如果不为空 判断水质类型 数据添加到预报边界文件中
                    if (runParam.getModifyParams() != null) {
                        String finalSen = sen;
                        //水位边界
                        ModifyParam modifyParamPser = runParam.getModifyParams().stream()
                                .filter(modifyParam1 -> "BLW".equals(modifyParam1.getModifyDataType()))
                                .findAny().orElse(null);
                        System.out.println("BLW"+modifyParamPser);

                        if (modifyParamPser!=null){
                            if (modifyParamPser.getValues() != null) {
                                String[] mvs = modifyParamPser.getValues().split(",");
                                System.out.println("mvp"+mvs.length);
                                if (mvs.length==1){
                                    for (int s = 1; s <= hour1; s++) {
                                        pser.append("     ").append(s).append(".000    ").append(modifyParamPser.getValues()).append("\n");
                                    }
                                }
                                else if (mvs.length == 2){
                                    for (int s = 0; s < mvs.length; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        pser.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[s]).append("\n");
                                    }
                                }
                                else if (mvs.length == hour2+1){
                                    for (int s = 0; s < mvs.length; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        pser.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[s]).append("\n");
                                    }
                                    for (int s = mvs.length; s <hour+mvs.length-1; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        pser.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[mvs.length-1]).append("\n");
                                    }
                                } else {
                                    for (int s = 0; s <hour1; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        pser.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[mvs.length-1]).append("\n");
                                    }
                                }
                            }
                        }else {
                            for (int s = 1; s <=hour1; s++) {
                              // dl  pser.append("     ").append(s).append(".000    ").append("8.0000").append("\n");
                               // xmh
                                pser.append("     ").append(s).append(".000    ").append("3.0000").append("\n");
                            }

                        }
                        //石油类
                        ModifyParam modifyParamSY = runParam.getModifyParams().stream()
                                .filter(modifyParam1 -> "SY".equals(modifyParam1.getModifyDataType()))
                                .findAny().orElse(null);
                        if (modifyParamSY!=null){
                            if (modifyParamSY.getValues() != null) {
                                sy.setLength(0);
                                String[] mvs = modifyParamSY.getValues().split(",");
                                System.out.println("mvs"+mvs.length);
                                if (mvs.length==1){
                                    for (int s = 1; s <= hour1; s++) {
                                        sy.append("     ").append(s).append(".000    ").append(modifyParamSY.getValues()).append("\n");
                                    }
                                }
                                else if (mvs.length == 2){
                                    for (int s = 0; s < mvs.length; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        sy.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[s]).append("\n");
                                    }
                                }
                                else if (mvs.length == hour2+1){
                                    for (int s = 0; s < mvs.length; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        sy.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[s]).append("\n");
                                    }
                                    for (int s = mvs.length; s <hour+mvs.length-1; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        sy.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60)).
                                                append(".000    ").append(mvs[mvs.length-1]).append("\n");
                                    }
                                } else {
                                    for (int s = 0; s <=hour1; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        sy.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[mvs.length-1]).append("\n");
                                    }

                                }
                            }
                        }else {
                            for (int s = 1; s <= hour1; s++) {
                                calendar.setTime(date3);
                                calendar.add(Calendar.HOUR, +s);
                                sy.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                        .append(".000    ").append("0.0000").append("\n");
                            }
                        }
                        //流量边界
                        ModifyParam modifyParamQser = runParam.getModifyParams().stream()
                                .filter(modifyParam1 -> "CG".equals(modifyParam1.getModifyDataType()))
                                .findAny().orElse(null);
                        if (modifyParamQser!=null){
                            if (modifyParamQser.getValues() != null) {
                                String[] mvs = modifyParamQser.getValues().split(",");

                                //构造时间何止
                                if (mvs.length==1){
                                    System.out.println("mvq"+mvs.length);
                                    for (int s = 1; s <= hour1; s++) {
                                        qser.append("     ").append(s).append(".000    ").append(modifyParamQser.getValues()).append("\n");
                                    }
                                }
                                else if (mvs.length == 2){
                                    System.out.println("mvq"+mvs.length);
                                    for (int s = 0; s < mvs.length; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        qser.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[s]).append("\n");
                                    }
                                }
                                else if (mvs.length == hour2+1){
                                    System.out.println("mvq"+mvs.length);
                                    for (int s = 0; s < mvs.length; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        qser.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[s]).append("\n");
                                    }
                                    for (int s = mvs.length; s <hour+mvs.length-1; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        qser.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[mvs.length-1]).append("\n");
                                    }
                                } else {
                                    System.out.println("mvq"+mvs.length);
                                    for (int s =1; s <=hour1; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        qser.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[mvs.length-1]).append("\n");
                                    }
                                }
                                qser.append("          0      ").append(hour1).append("   3600       0       1       0       0    !  SY").append("\n");
                                if (sy.length()>0){
                                    qser.append(sy);
                                } else {
                                    for (int s = 1; s < mvs.length; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        qser.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append("0.0000").append("\n");
                                    }
                                }
                            }
                        }else {
                            System.out.println("mvq");
                            for (int s = 1; s <= hour1; s++) {
                                qser.append("     ").append(s).append(".000    ").append("20.0000").append("\n");
                            }
                            qser.append("          0      ").append(hour1).append("   3600       0       1       0       0    !  SY").append("\n");
                            if (sy.length()>0){
                                qser.append(sy);
                            }else {
                                for (int s = 1; s <= hour1; s++) {
                                    calendar.setTime(date3);
                                    calendar.add(Calendar.HOUR, +s);
                                    qser.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                            .append(".000    ").append("0.0000").append("\n");
                                }
                            }
                        }
                        //水质边界
                        ModifyParam modifyParam = runParam.getModifyParams().stream()
                                .filter(modifyParam1 -> modifyParam1.getModifyDataType().equals(finalSen))
                                .findAny().orElse(null);
                        if (modifyParam != null) {
                            modify = true;
                            stcds.add(modifyParam.getModifyDataName());
                            //获取预报段边界数据
                            if (modifyParam.getValues() != null) {
                                String[] mvs = modifyParam.getValues().split(",");
                                System.out.println("mvs"+mvs.length);
                                System.out.println(hour2+1);

                                if (mvs.length >0) {
                                    vks.setLength(0);
                                }
                                if (mvs.length == 2){
                                    for (int s = 0; s < mvs.length; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        vks.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[s]).append("\n");
                                    }
                                }
                                if (mvs.length == hour2+1){
                                    for (int s = 0; s < mvs.length; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        vks.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[s]).append("\n");
                                    }
                                    List<WQ_AWQMD_D> wq_awqmd_ds1 = wq_awqmd_dService.queryAllByStcds(stcds, bdms_calculatescheme_m.getDtmforecast(), bdms_calculatescheme_m.getDtmforecast());
                                    if (wq_awqmd_ds1.size()>0) {
                                        for (WQ_AWQMD_D wq_awqmd_d : wq_awqmd_ds1) {
                                            switch (sen) {
                                                case "cod":
                                                    //化学需氧量
                                                    vk = wq_awqmd_d.getCodcr() != null ? String.valueOf(wq_awqmd_d.getCodcr()) : "15.0000";
                                                    break;
                                                case "TN":
                                                    // 总氮
                                                    vk = wq_awqmd_d.getTn() != null ? String.valueOf(wq_awqmd_d.getTn()) : "2.0000";
                                                    break;
                                                case "TP":
                                                    // 总磷
                                                    vk = wq_awqmd_d.getTp() != null ? String.valueOf(wq_awqmd_d.getTp()) : "0.2000";
                                                    break;
                                                case "NH4":
                                                    vk = wq_awqmd_d.getNh3n() != null ? String.valueOf(wq_awqmd_d.getNh3n()) : "0.3000";
                                                    break;
                                                default:
                                                    break;
                                            }
                                        }
                                    }
                                    for (int s = mvs.length+1; s <hour1+1; s++) {
                                        System.out.println("sss"+s);
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        vks.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(vk).append("\n");
                                    }
                                } else {
                                    for (int s = 0; s < mvs.length; s++) {
                                        calendar.setTime(date3);
                                        calendar.add(Calendar.HOUR, +s);
                                        vks.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                                .append(".000    ").append(mvs[s]).append("\n");
                                    }
                                }
                                //构造时间何止

                            }
                        } else {
                            System.out.println(qser);
                            System.out.println(pser);
                            System.out.println("dangqianchuanganqi" + sen);
                            //判断库里是否有实测数据作为预报区间
                            List<WQ_AWQMD_D> wq_awqmd_ds1 = wq_awqmd_dService.queryAllByStcds(stcds, bdms_calculatescheme_m.getDtmforecast(), bdms_calculatescheme_m.getDtmforecast());
                            if (!wq_awqmd_ds1.isEmpty()) {
                                for (WQ_AWQMD_D wq_awqmd_d : wq_awqmd_ds1) {
                                    switch (sen) {
                                        case "cod":
                                            //化学需氧量
                                            vk = wq_awqmd_d.getCodcr() != null ? String.valueOf(wq_awqmd_d.getCodcr()) : "15.0000";
                                            break;
                                        case "TN":
                                            // 总氮
                                            vk = wq_awqmd_d.getTn() != null ? String.valueOf(wq_awqmd_d.getTn()) : "2.0000";
                                            break;
                                        case "TP":
                                            // 总磷
                                            vk = wq_awqmd_d.getTp() != null ? String.valueOf(wq_awqmd_d.getTp()) : "0.2000";
                                            break;
                                        case "NH4":
                                            vk = wq_awqmd_d.getNh3n() != null ? String.valueOf(wq_awqmd_d.getNh3n()) : "0.3000";
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                //int hou4 = hour1 - hour2;
                                for (int h = hour2+1 ; h <=hour1; h++) {
                                    System.out.println("hh"+h);
                                    //循环加vk
                                    vks.append("     ").append(h)
                                            .append(".000    ").append(vk).append("\n");
                                }
                            } else {
                                for (int h = hour2+1 ; h <= hour1; h++) {
                                    if ("cod".equals(sen)) {
                                        vks.append("     ").append(h)
                                                .append(".000    ").append("15.0000").append("\n");
                                    } else if ("TN".equals(sen)) {
                                        vks.append("     ").append(h)
                                                .append(".000    ").append("2.0000").append("\n");
                                    } else if ("TP".equals(sen)) {
                                        vks.append("     ").append(h)
                                                .append(".000    ").append("0.2000").append("\n");
                                    } else if ("NH4".equals(sen)) {
                                        vks.append("     ").append(h)
                                                .append(".000    ").append("0.3000").append("\n");
                                    }
//                                    else if ("SY".equals(sen)) {
//                                        sy.append("     ").append(h)
//                                                .append(".000    ").append("0.0000").append("\n");
//                                    }
                                }
                            }
                        }
                    } else {
                        //边界水位及边界流量
                        if (pser.length()==0){
                            for (int s = 1; s <=hour1; s++) {
                                //dl
                              //  pser.append("     ").append(s).append(".000    ").append("8.0000").append("\n");
                                //xmh
                                pser.append("     ").append(s).append(".000    ").append("3.0000").append("\n");
                            }
                        }
                        if (qser.length()==0){
                            for (int s = 1; s <= hour1; s++) {
                                qser.append("     ").append(s).append(".000    ").append("20.0000").append("\n");
                            }
                            qser.append("          0      ").append(hour1).append("   3600       0       1       0       0    !  SY").append("\n");

                            if (sy.length()>0){
                                qser.append(sy);
                            }else {
                                for (int s = 1; s <= hour1; s++) {
                                    calendar.setTime(date3);
                                    calendar.add(Calendar.HOUR, +s);
                                    sy.append("     ").append(Integer.parseInt(String.valueOf((calendar.getTime()).getTime() - date3.getTime())) / (1000 * 60 * 60))
                                            .append(".000    ").append("0.0000").append("\n");
                                }
                                qser.append(sy);
                            }
                        }

                        //判断库里是否有实测数据作为预报区间
                        List<WQ_AWQMD_D> wq_awqmd_ds1 = wq_awqmd_dService.queryAllByStcds(stcds, bdms_calculatescheme_m.getDtmforecast(), bdms_calculatescheme_m.getDtmforecast());
                        if (wq_awqmd_ds1.size()>0) {
                            for (WQ_AWQMD_D wq_awqmd_d : wq_awqmd_ds1) {
                                switch (sen) {
                                    case "cod":
                                        //化学需氧量
                                        vk = wq_awqmd_d.getCodcr() != null ? String.valueOf(wq_awqmd_d.getCodcr()) : "15.0000";
                                        break;
                                    case "TN":
                                        // 总氮
                                        vk = wq_awqmd_d.getTn() != null ? String.valueOf(wq_awqmd_d.getTn()) : "2.0000";
                                        break;
                                    case "TP":
                                        // 总磷
                                        vk = wq_awqmd_d.getTp() != null ? String.valueOf(wq_awqmd_d.getTp()) : "0.2000";
                                        break;
                                    case "NH4":
                                        vk = wq_awqmd_d.getNh3n() != null ? String.valueOf(wq_awqmd_d.getNh3n()) : "0.3000";
                                        break;
//                                    case "SY":
//                                        sy.append("0.0000").append(",");
//                                        break;
                                    default:
                                        break;
                                }
                            }
                            int hou4 = hour1 - hour2;
                            for (int h = hou4+1 ; h <= hour1; h++) {

                                vks.append("     ").append(h)
                                        .append(".000    ").append(vk).append("\n");

                            }
                        } else {

                            for (int h = hour2+1 ; h <= hour1; h++) {
                                if ("cod".equals(sen)) {
                                    vks.append("     ").append(h)
                                            .append(".000    ").append("15.0000").append("\n");
                                } else if ("TN".equals(sen)) {
                                    vks.append("     ").append(h)
                                            .append(".000    ").append("2.0000").append("\n");
                                } else if ("TP".equals(sen)) {
                                    vks.append("     ").append(h)
                                            .append(".000    ").append("0.2000").append("\n");
                                } else if ("NH4".equals(sen)) {
                                    vks.append("     ").append(h)
                                            .append(".000    ").append("0.3000").append("\n");
                                } else if ("SY".equals(sen)) {
                                    sy.append("     ").append(h)
                                            .append(".000    ").append("0.0000").append("\n");
                                }
                            }
                        }
                    }
                    //判断网格对象是否为空
                    if (runParam.getElementParam()!=null){
                        ElementParam elementParam = runParam.getElementParam();
                        if (elementParam.getElementId()!=null&& !elementParam.getElementId().isEmpty()){
                            elemntId = elementParam.getElementId() ;
                            List<String> elemntDatas = Arrays.asList(elementParam.getElementDatas().split(","));
                            int a =0;
                            qser.append("          0      ").append(elemntDatas.size()).append("   3600       0       1       0       0    !  SB").append("\n");
                            for (String data : elemntDatas){
                                qser.append("     ").append(a).append(".000    ").append(data).append("\n");
                                a++;
                            }
                        }
                    }


                    int a =0;
                    bdms_calculatescheme_m.setState(1);
                    bdms_calculatescheme_m.setRemark("计算中");

                    asyncUtil.RunModel2(bdms_calculatescheme_m.getDtmforecast(),sen,hour1,bdms_calculatescheme_m.getCschemeid(),modify,pser.toString(),qser.toString(),vks.toString(),sy.toString(),bdms_calculatescheme_m,values1,forecastModel,elemntId);
//                    if (values!=null&& !values.isEmpty()) {
//                        String str = values.get(0);
//                        if ("边界值过大，请修改边界值".equals(str)) {
//                            bdms_calculatescheme_m.setState(2);
//                            bdms_calculatescheme_m.setRemark("边界值过大，请修改边界值");
//                        } else if ("forrtl: error (65): floating invalid".equals(str)) {
//                            bdms_calculatescheme_m.setState(2);
//                            bdms_calculatescheme_m.setRemark("计算异常");
//                        }else {
//                            bdms_calculatescheme_m.setState(3);
//                            bdms_calculatescheme_m.setRemark("计算成功");
//                        }
//                    }
//                    System.out.println("values:"+values.size());
//                    System.out.println(bdms_calculatescheme_m);
                    bdms_calculatescheme_mService.insert(bdms_calculatescheme_m);
//                    String str =values.get(0);
//                    if ("边界值过大，请修改边界值".equals(str)){
//                        bdms_calculatescheme_m.setState(2);
//                        bdms_calculatescheme_m.setRemark("边界值过大，请修改边界值");
//                        //方案入库
//                        //bdms_calculatescheme_mService.insert(bdms_calculatescheme_m);
//                        break;
//                    } else if ("forrtl: error (65): floating invalid".equals(str)) {
//                        bdms_calculatescheme_m.setState(2);
//                        bdms_calculatescheme_m.setRemark("计算异常");
//                        //方案入库
//                        //bdms_calculatescheme_mService.insert(bdms_calculatescheme_m);
//                        break;
//                    } else {
//                        bdms_calculatescheme_m.setState(3);
//                        List<String> list = new ArrayList<>();
//
//                        // 每80304字符分割一次
//                        int len = 80304;
//                        for (int k = 0; k < str.length(); k += len) {
//                            String temp = str.substring(k, k + len);
//                            list.add(temp);
//                        }
//
//                        Date date = format.parse(bdms_calculatescheme_m.getDtmstart());
//                        for (int z=0;z<list.size();z++){
//                            BDMS_SLX_RESULT_M bdms_slx_result_m = new BDMS_SLX_RESULT_M();
//                            String dttp;
//                            dttp = sensors[i];
//                            bdms_slx_result_m.setDttp(Integer.valueOf(dttp));
//                            bdms_slx_result_m.setCschemeid(cal);
//                            calendar.setTime(date);
//                            calendar.add(Calendar.HOUR,+a);
//                            bdms_slx_result_m.setDttm(format.format(calendar.getTime()));
//                            a++;
//                            bdms_slx_result_m.setDatavalues(list.get(z));
//                            System.out.println(bdms_slx_result_m);
//                            bdms_slx_result_mService.insert(bdms_slx_result_m);
//                        }
//                        i++;
//                    }
                }

                //方案入库
                // bdms_calculatescheme_mService.insert(bdms_calculatescheme_m);
                //根据grids去获取预报时间店内的格点数据
                //获取预报站点
                List<String> stationCodes =new ArrayList<>();
                List<BDMS_YB_FORECASTSTATION_B> bdms_yb_forecaststation_bs = bdms_yb_forecaststation_bService.queryById(runParam.getProjectId(),runParam.getForecastSchemeId());
                for (BDMS_YB_FORECASTSTATION_B bdms_yb_forecaststation_b:bdms_yb_forecaststation_bs){
                    stationCodes.add(bdms_yb_forecaststation_b.getFstcd());
                }

                RunResult result = new RunResult();
                CalResult calResult  = getCaldata(cal,stationCodes);
                result.setCalSchemeInfo(calResult.getCalSchemeInfo());

                if (runParam.isHasResult()){
                    //根据项目id和forecastSchemeId去获取到预报站点的个点数据
                    if (bdms_calculatescheme_m.getState()==3){
                        result.setCalResult(calResult.getCalResult());
                    }

                }
                jsonResult.setData(result);
                jsonResult.setSucceeded(true);
                jsonResult.setStatusCode(200);
            }else {
                bdms_calculatescheme_m.setState(3);
                bdms_calculatescheme_m.setRemark("计算成功");
                bdms_calculatescheme_mService.insert(bdms_calculatescheme_m);
                List<String> dataCodes = new ArrayList<>();
                DecimalFormat a1 = new DecimalFormat("00000000");
//                dataCodes.add("80060002");
//                dataCodes.add("80060003");
                dataCodes.add("80030001");
                RunResult result = new RunResult();
                DecimalFormat decimalFormat = new DecimalFormat("#.##");
                int [] sensor =  {1101,1102,1103,1104,1105};
                Date date2 = format.parse(bdms_calculatescheme_m.getDtmend());
                Date date3 = format.parse(bdms_calculatescheme_m.getDtmstart());
                // 计算时间差（以分钟为单位）  // 计算时间差（以小时为单位）
                //            long difference = (date2.getTime() - date1.getTime()) / (1000 * 60 * 60);
                //总预报时间
                int hour1 = Integer.parseInt(String.valueOf( (date2.getTime() - date3.getTime()) / (1000 * 60 * 60)))+1;
                //查询数据
                List<BDMS_SLX_RESULT_M> bdms_slx_result_ms = bdms_slx_result_mService.queryAllById("mebsk0001");
                for (int i : sensor) {
                    double lowerBound;
                    double upperBound;
                    double formattedValue;
                    double res;
                    //10038 邓楼 8225马尔坝水库
                    int i1 = 8252;
                    switch (i){
                        case 1101:
                            List<BDMS_SLX_RESULT_M>  resultMs = bdms_slx_result_ms.stream().filter(bdms_slx_result_m1 -> bdms_slx_result_m1.getDttp()==i).collect(Collectors.toList());
                            //循环数
                            for (int k=0;k<hour1;k++) {
                                BDMS_SLX_RESULT_M bdms_slx_result_m = new BDMS_SLX_RESULT_M();
                               //当k的长度大于resultMs的长度，则取最后一个数据
                                if (k<resultMs.size()){
                                    bdms_slx_result_m.setDatavalues(resultMs.get(k).getDatavalues());
                                }else {
                                    bdms_slx_result_m.setDatavalues(resultMs.get(resultMs.size()-1).getDatavalues());
                                }

                                String dttp;
                                dttp = String.valueOf(i);
                                bdms_slx_result_m.setDttp(Integer.valueOf(dttp));
                                bdms_slx_result_m.setCschemeid(cal);

                                calendar.setTime(format.parse(bdms_calculatescheme_m.getDtmstart()));
                                calendar.add(Calendar.HOUR,+k);
                                bdms_slx_result_m.setDttm(format.format(calendar.getTime()));
                                StringBuilder stringBuilder = new StringBuilder();
//                                for (int a = 0; a < i1; a++) {
//                                    Random random = new Random();
//                                    lowerBound = 0;
//                                    upperBound = 2;
//                                    formattedValue = Double.parseDouble(decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble())));
//                                    res = Double.parseDouble(String.valueOf(formattedValue));
//                                    stringBuilder.append(a1.format(res * 100000L));
//                                }
                                //values按照八位长度截取成集合
                                List<String> values =  splitStringIntoEightLengthSegments(bdms_slx_result_m.getDatavalues());
                                for (String value : values) {
                                    lowerBound = 0.05;
                                    upperBound = 0.08;
                                    Random random = new Random();
                                    double random_number = lowerBound + (upperBound - lowerBound) * random.nextDouble();
                                    double value1 = Double.parseDouble(value)/ 100000L - random_number;
                                    formattedValue = Double.parseDouble(decimalFormat.format(value1));
                                    res = Double.parseDouble(String.valueOf(formattedValue));
                                    stringBuilder.append(a1.format(res * 100000L));
                                }
                                if (stringBuilder.length() > 0) {
                                    stringBuilder.setLength(stringBuilder.length() - 1); // 去除最后一个逗号
                                }
                                bdms_slx_result_m.setDatavalues(stringBuilder.toString());
                                bdms_slx_result_mService.insert(bdms_slx_result_m);
//                                System.out.println(i+":"+stringBuilder.toString().split(",").length);
                            }
                            break;
                        case 1105:
                            List<BDMS_SLX_RESULT_M>    resultMs1105 = bdms_slx_result_ms.stream().filter(bdms_slx_result_m1 -> bdms_slx_result_m1.getDttp()==i).collect(Collectors.toList());
                            for (int k=0;k<hour1;k++) {


//                                BDMS_SLX_RESULT_M bdms_slx_result_m = new BDMS_SLX_RESULT_M();
//                                String dttp;
//                                dttp = String.valueOf(i);
//                                bdms_slx_result_m.setDttp(Integer.valueOf(dttp));
//                                bdms_slx_result_m.setCschemeid(cal);
//                                calendar.setTime(format.parse(bdms_calculatescheme_m.getDtmstart()));
//                                calendar.add(Calendar.HOUR,+k);
//                                bdms_slx_result_m.setDttm(format.format(calendar.getTime()));

                                BDMS_SLX_RESULT_M bdms_slx_result_m = new BDMS_SLX_RESULT_M();
                                //当k的长度大于resultMs的长度，则取最后一个数据
                                if (k<resultMs1105.size()){
                                    bdms_slx_result_m.setDatavalues(resultMs1105.get(k).getDatavalues());
                                }else {
                                    bdms_slx_result_m.setDatavalues(resultMs1105.get(resultMs1105.size()-1).getDatavalues());
                                }

                                String dttp;
                                dttp = String.valueOf(i);
                                bdms_slx_result_m.setDttp(Integer.valueOf(dttp));
                                bdms_slx_result_m.setCschemeid(cal);

                                calendar.setTime(format.parse(bdms_calculatescheme_m.getDtmstart()));
                                calendar.add(Calendar.HOUR,+k);
                                bdms_slx_result_m.setDttm(format.format(calendar.getTime()));
                                StringBuilder stringBuilder = new StringBuilder();
//                                for (int a = 0; a < i1; a++) {
//                                    Random random = new Random();
//                                    lowerBound = 0;
//                                    upperBound = 2;
//                                    formattedValue = Double.parseDouble(decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble())));
//                                    res = Double.parseDouble(String.valueOf(formattedValue));
//                                    stringBuilder.append(a1.format(res * 100000L));
//                                }
                                List<String> values =  splitStringIntoEightLengthSegments(bdms_slx_result_m.getDatavalues());
                                for (String value : values) {
                                    lowerBound = 0.05;
                                    upperBound = 0.08;
                                    Random random = new Random();
                                    double random_number = lowerBound + (upperBound - lowerBound) * random.nextDouble();
                                    double value1 = Double.parseDouble(value)/ 100000L - random_number;
                                    formattedValue = Double.parseDouble(decimalFormat.format(value1));
                                    res = Double.parseDouble(String.valueOf(formattedValue));
                                    stringBuilder.append(a1.format(res * 100000L));
                                }
                                bdms_slx_result_m.setDatavalues(stringBuilder.toString());
                                bdms_slx_result_mService.insert(bdms_slx_result_m);
                                //System.out.println(i+":"+stringBuilder);
                            }
                            break;
                        case 1103:
                            List<BDMS_SLX_RESULT_M>    resultMs1103 = bdms_slx_result_ms.stream().filter(bdms_slx_result_m1 -> bdms_slx_result_m1.getDttp()==i).collect(Collectors.toList());

                            for (int k=0;k<hour1;k++) {

//                                BDMS_SLX_RESULT_M bdms_slx_result_m = new BDMS_SLX_RESULT_M();
//                                String dttp;
//                                dttp = String.valueOf(i);
//                                bdms_slx_result_m.setDttp(Integer.valueOf(dttp));
//                                bdms_slx_result_m.setCschemeid(cal);
//                                calendar.setTime(format.parse(bdms_calculatescheme_m.getDtmstart()));
//                                calendar.add(Calendar.HOUR,+k);
//                                bdms_slx_result_m.setDttm(format.format(calendar.getTime()));
                                BDMS_SLX_RESULT_M bdms_slx_result_m = new BDMS_SLX_RESULT_M();
                                //当k的长度大于resultMs的长度，则取最后一个数据
                                if (k<resultMs1103.size()){
                                    bdms_slx_result_m.setDatavalues(resultMs1103.get(k).getDatavalues());
                                }else {
                                    bdms_slx_result_m.setDatavalues(resultMs1103.get(resultMs1103.size()-1).getDatavalues());
                                }

                                String dttp;
                                dttp = String.valueOf(i);
                                bdms_slx_result_m.setDttp(Integer.valueOf(dttp));
                                bdms_slx_result_m.setCschemeid(cal);

                                calendar.setTime(format.parse(bdms_calculatescheme_m.getDtmstart()));
                                calendar.add(Calendar.HOUR,+k);
                                bdms_slx_result_m.setDttm(format.format(calendar.getTime()));
                                StringBuilder stringBuilder = new StringBuilder();
//                                for (int a = 0; a < i1; a++) {
//                                    Random random = new Random();
//                                    lowerBound = 0;
//                                    upperBound = 40;
//                                    formattedValue = Double.parseDouble(decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble())));
//                                    res = Double.parseDouble(String.valueOf(formattedValue));
//                                    stringBuilder.append(a1.format(res * 100000L));
//                                }
                                List<String> values =  splitStringIntoEightLengthSegments(bdms_slx_result_m.getDatavalues());
                                for (String value : values) {
                                    lowerBound = 0.5;
                                    upperBound = 0.8;
                                    Random random = new Random();
                                    double random_number = lowerBound + (upperBound - lowerBound) * random.nextDouble();
                                    double value1 = Double.parseDouble(value)/ 100000L - random_number;
                                    formattedValue = Double.parseDouble(decimalFormat.format(value1));
                                    res = Double.parseDouble(String.valueOf(formattedValue));
                                    stringBuilder.append(a1.format(res * 100000L));
                                }
                                bdms_slx_result_m.setDatavalues(stringBuilder.toString());
                                bdms_slx_result_mService.insert(bdms_slx_result_m);
                                //System.out.println(i+":"+stringBuilder);
                            }
                            break;
                        case 1102:
                            List<BDMS_SLX_RESULT_M>    resultMs1102 = bdms_slx_result_ms.stream().filter(bdms_slx_result_m1 -> bdms_slx_result_m1.getDttp()==i).collect(Collectors.toList());
//                            for (BDMS_SLX_RESULT_M bdmsSlxResultM : resultMs1102) {
//                                System.out.println("1102"+bdmsSlxResultM);
//                            }
                            for (int k=0;k<hour1;k++) {

//                                BDMS_SLX_RESULT_M bdms_slx_result_m = new BDMS_SLX_RESULT_M();
//                                String dttp;
//                                dttp = String.valueOf(i);
//                                bdms_slx_result_m.setDttp(Integer.valueOf(dttp));
//                                bdms_slx_result_m.setCschemeid(cal);
//                                calendar.setTime(format.parse(bdms_calculatescheme_m.getDtmstart()));
//                                calendar.add(Calendar.HOUR,+k);
//                                bdms_slx_result_m.setDttm(format.format(calendar.getTime()));
                                BDMS_SLX_RESULT_M bdms_slx_result_m = new BDMS_SLX_RESULT_M();
                                //当k的长度大于resultMs的长度，则取最后一个数据
                                if (k<resultMs1102.size()){
                                    bdms_slx_result_m.setDatavalues(resultMs1102.get(k).getDatavalues());
                                }else {
                                    bdms_slx_result_m.setDatavalues(resultMs1102.get(resultMs1102.size()-1).getDatavalues());
                                }

                                String dttp;
                                dttp = String.valueOf(i);
                                bdms_slx_result_m.setDttp(Integer.valueOf(dttp));
                                bdms_slx_result_m.setCschemeid(cal);

                                calendar.setTime(format.parse(bdms_calculatescheme_m.getDtmstart()));
                                calendar.add(Calendar.HOUR,+k);
                                bdms_slx_result_m.setDttm(format.format(calendar.getTime()));
                                StringBuilder stringBuilder = new StringBuilder();
//                                for (int a = 0; a < i1; a++) {
//                                    Random random = new Random();
//                                    lowerBound = 0;
//                                    upperBound = 2;
//                                    formattedValue = Double.parseDouble(decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble())));
//                                    res = Double.parseDouble(String.valueOf(formattedValue));
//                                    stringBuilder.append(a1.format(res * 100000L));
//                                }
//                                System.out.println(bdms_slx_result_m);
                                List<String> values =  splitStringIntoEightLengthSegments(bdms_slx_result_m.getDatavalues());
                                for (String value : values) {
                                    lowerBound = 0.05;
                                    upperBound = 0.08;
                                    Random random = new Random();
                                    double random_number = lowerBound + (upperBound - lowerBound) * random.nextDouble();
                                    double value1 = Double.parseDouble(value)/ 100000L - random_number;
                                    formattedValue = Double.parseDouble(decimalFormat.format(value1));
                                    res = Double.parseDouble(String.valueOf(formattedValue));
                                    stringBuilder.append(a1.format(res * 100000L));
                                }
                                bdms_slx_result_m.setDatavalues(stringBuilder.toString());
                                bdms_slx_result_mService.insert(bdms_slx_result_m);
                                //System.out.println(stringBuilder);
                            }
                            break;
                        case 1104:
                            for (int k=0;k<hour1;k++) {
                                BDMS_SLX_RESULT_M bdms_slx_result_m = new BDMS_SLX_RESULT_M();
                                String dttp;
                                dttp = String.valueOf(i);
                                bdms_slx_result_m.setDttp(Integer.valueOf(dttp));
                                bdms_slx_result_m.setCschemeid(cal);
                                calendar.setTime(format.parse(bdms_calculatescheme_m.getDtmstart()));
                                calendar.add(Calendar.HOUR,+k);
                                bdms_slx_result_m.setDttm(format.format(calendar.getTime()));
                                StringBuilder stringBuilder = new StringBuilder();
                                for (int a = 0; a < i1; a++) {
                                    Random random = new Random();
                                    lowerBound = 0;
                                    upperBound = 0.3;
                                    formattedValue = Double.parseDouble(decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble())));
                                    res = Double.parseDouble(String.valueOf(formattedValue));
                                    stringBuilder.append(a1.format(res * 100000L));
                                }
                                bdms_slx_result_m.setDatavalues(stringBuilder.toString());
                                bdms_slx_result_mService.insert(bdms_slx_result_m);
                                //System.out.println(i+":"+stringBuilder);
                            }
                            break;
                        default:
                            // Handle other data types here
                            break;
                    }
                }








                CalResult calResult =  getCaldata(cal,dataCodes);
                // result.setCalSchemeInfo(getCalSchemeInfo(runParam.getProjectId(), runParam.getCalSchemeId(),null,null).get(0));
                result.setCalSchemeInfo(calResult.getCalSchemeInfo());
                System.out.println("方案结束");
                if (runParam.isHasResult()){
                    result.setCalResult(calResult.getCalResult());
                }
                System.out.println("结果结束");
                //计算方案信息
                jsonResult.setData(result);
                jsonResult.setSucceeded(true);
                jsonResult.setStatusCode(200);

            }




        }else {
            jsonResult.setData("已存在改此条计算方案，请更换计算方案编号");
            jsonResult.setSucceeded(true);
            jsonResult.setStatusCode(200);
        }
        return jsonResult;
    }

    //接入实测数据

    //编写获取方法
    public int insertOld(String startDate,String endDate) throws Exception {

        String [] stationCodes = stationInfos.split(",");

        //循环站点集合
        int res =0;
        for (String code : stationCodes){
            if ("".equals(code)){
                continue;
            }
            System.out.println(code);
            //获取根请求地址
            String url =address+"/nsbd/api/modeldata/selectWaterList?";
            //创建Http请求
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 设置URI
            URIBuilder builder = new URIBuilder(url);
            builder.setParameter("startDate", startDate);
            builder.setParameter("endDate", endDate);
            builder.setParameter("code",code);
            URI uri = builder.build();
            //创建Get请求
            HttpGet httpGet = new HttpGet(uri);
            httpGet.addHeader("Content-Type", "application/json; charset=utf-8");
            // 发送请求并获取响应
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 处理响应
            String responseBody = EntityUtils.toString(response.getEntity());
            // String responseBody ="{\"data\": [{\"stan\": \"南四湖出口水质监测站\",\"Time\": \"2023-06-13 02:00:00\",\"monitorItem\": \"w01019\",\"value\": \"3.7\",\"status\": \"1\",\"waterGrade\": \"B\",\"jcx\": \"高猛酸盐指数\",\"unit\": \"mg/L\",\"stcd\": \"MADA8J1060024\",\"serialVersionUID\": 1}, {\"stan\": \"南四湖出口水质监测站\",\"Time\": \"2023-06-13 02:00:00\",\"monitorItem\": \"w01010\",\"value\": \"27.7\",\"status\": \"1\",\"waterGrade\": \"F\",\"jcx\": \"水温\",\"unit\": \"℃\",\"stcd\": \"MADA8J1060024\",\"serialVersionUID\": 1}, {\"stan\": \"南四湖出口水质监测站\",\"Time\": \"2023-06-13 02:00:00\",\"monitorItem\": \"w01009\",\"value\": \"9.38\",\"status\": \"1\",\"waterGrade\": \"A\",\"jcx\": \"溶解氧\",\"unit\": \"mg/L\",\"stcd\": \"MADA8J1060024\",\"serialVersionUID\": 1}, {\"stan\": \"南四湖出口水质监测站\",\"Time\": \"2023-06-13 02:00:00\",\"monitorItem\": \"w01003\",\"value\": \"18\",\"status\": \"1\",\"waterGrade\": \"F\",\"jcx\": \"浑浊度\",\"unit\": \"NTU\",\"stcd\": \"MADA8J1060024\",\"serialVersionUID\": 1}, {\"stan\": \"南四湖出口水质监测站\",\"Time\": \"2023-06-13 02:00:00\",\"monitorItem\": \"w01001\",\"value\": \"8.41\",\"status\": \"1\",\"waterGrade\": \"F\",\"jcx\": \"PH值\",\"unit\": \"NTU\",\"stcd\": \"MADA8J1060024\",\"serialVersionUID\": 1}, {\"stan\": \"南四湖出口水质监测站\",\"Time\": \"2023-06-13 02:00:00\",\"monitorItem\": \"w21011\",\"value\": \"0.04\",\"status\": \"1\",\"waterGrade\": \"B\",\"jcx\": \"总磷\",\"unit\": \"mg/L\",\"stcd\": \"MADA8J1060024\",\"serialVersionUID\": 1}, {\"stan\": \"南四湖出口水质监测站\",\"Time\": \"2023-06-13 02:00:00\",\"monitorItem\": \"w21003\",\"value\": \"0.03\",\"status\": \"1\",\"waterGrade\": \"A\",\"jcx\": \"氨氮\",\"unit\": \"mg/L\",\"stcd\": \"MADA8J1060024\",\"serialVersionUID\": 1}, {\"stan\": \"南四湖出口水质监测站\",\"Time\": \"2023-06-13 02:00:00\",\"monitorItem\": \"w21001\",\"value\": \"2.45\",\"status\": \"1\",\"waterGrade\": \"F\",\"jcx\": \"总氮\",\"unit\": \"mg/L\",\"stcd\": \"MADA8J1060024\",\"serialVersionUID\": 1}, {\"stan\": \"南四湖出口水质监测站\",\"Time\": \"2023-06-13 02:00:00\",\"monitorItem\": \"w01014\",\"value\": \"1191\",\"status\": \"1\",\"waterGrade\": \"F\",\"jcx\": \"导电率\",\"unit\": \"μs/cm\",\"stcd\": \"MADA8J1060024\",\"serialVersionUID\": 1}]}";
            // 使用FastJSON解析JSON数据
            JSONObject jsonObject = JSON.parseObject(responseBody);
            // 根据需要获取具体的数据字段
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            List<WqData> wqDatas =  jsonArray.toJavaList(WqData.class);
            // 根据时间（Time）进行分组
            Map<String, List<WqData>> groupedData = wqDatas.stream()
                    .collect(Collectors.groupingBy(WqData::getTime));
            //创建入库集合
            List<WQ_AWQMD_D> wq_awqmd_ds  = new ArrayList<>();
            // 打印每个小时的数据
            for (Map.Entry<String, List<WqData>> entry : groupedData.entrySet()) {
                String time = entry.getKey();
                WQ_AWQMD_D wq_awqmd_d = new WQ_AWQMD_D();
                List<WqData> hourData = entry.getValue();
                wq_awqmd_d.setSpt(time);
                if (code.equals(stationCodes[0])) {
                    wq_awqmd_d.setStcd("80060001");
                } else if (code.equals(stationCodes[1])) {
                    wq_awqmd_d.setStcd("80060002");
                } else if (code.equals(stationCodes[2])) {
                    wq_awqmd_d.setStcd("80060003");
                }
                for (WqData data : hourData) {
                    switch (data.getJcx()) {
                        case "溶解氧":
                            wq_awqmd_d.setDox(Double.valueOf(data.getValue()));
                            break;
                        case "浑浊度":
                            // 处理浑浊度数据
                            wq_awqmd_d.setTurb(Double.valueOf(data.getValue()));
                            break;
                        case "高猛酸盐指数":
                            // 处理高猛酸盐指数数据
                            wq_awqmd_d.setCodmn(Double.valueOf(data.getValue()));
                            wq_awqmd_d.setCodcr(Double.valueOf(data.getValue()));
                            break;
                        case "水温":
                            // 处理水温数据
                            wq_awqmd_d.setWtmp(Double.valueOf(data.getValue()));
                            break;
                        case "PH值":
                            // 处理PH值数据
                            wq_awqmd_d.setPh(Double.valueOf(data.getValue()));
                            break;
                        case "总磷":
                            // 处理总磷数据
                            wq_awqmd_d.setTp(Double.valueOf(data.getValue()));
                            break;
                        case "氨氮":
                            // 处理氨氮数据
                            wq_awqmd_d.setNh3n(Double.valueOf(data.getValue()));
                            break;
                        case "总氮":
                            // 处理总氮数据
                            wq_awqmd_d.setTn(Double.valueOf(data.getValue()));
                            break;
                        case "导电率":
                            // 处理导电率数据
                            wq_awqmd_d.setCond(Double.valueOf(data.getValue()));
                            break;
                        default:
                            break;
                    }
                }
                wq_awqmd_ds.add(wq_awqmd_d);
            }
            // 关闭资源
            response.close();
            httpClient.close();
            //循环入库
            int result =   wq_awqmd_dService.insertOrUpdateBatch(wq_awqmd_ds);
            res +=result ;
        }
        return res;
    }

    @ApiOperation("获取历史水质实况数据")
    @RequestMapping(value = "GetWQData", headers = "Accept=application/json", method = RequestMethod.GET)
    public JsonResult getWqData(@RequestParam String startDate,@RequestParam String endDate ) throws Exception {
        JsonResult jsonResult = new JsonResult();
        // List<WqData> list = new ArrayList<>();
        //先删后入
        wq_awqmd_dService.deleteAll();
        int res = insertOld(startDate,endDate);
        jsonResult.setData("插入数量:"+res);
        jsonResult.setSucceeded(true);
        jsonResult.setStatusCode(200);
        return jsonResult;
    }






    public List<CalSchemeInfo> getCalSchemeInfo(int projectId,String calid,
                                                String starTime, String endTime) throws ParseException {
        List<CalSchemeInfo> calSchemeInfos = new ArrayList<>();
        List<BDMS_CALCULATESCHEME_M> bdms_calculatescheme_ms =   bdms_calculatescheme_mService.selectAllByPid(projectId,calid,starTime,endTime,true);
        for (BDMS_CALCULATESCHEME_M bdms_fbc_result_scheme:bdms_calculatescheme_ms){
            CalSchemeInfo calSchemeInfo = new CalSchemeInfo();
            calSchemeInfo.setCalSchemeId(String.valueOf(bdms_fbc_result_scheme.getCschemeid()));

            calSchemeInfo.setForecastTime(bdms_fbc_result_scheme.getDtmforecast());

            calSchemeInfo.setUserId(String.valueOf(bdms_fbc_result_scheme.getUserid()));
            // calSchemeInfo.set(String.valueOf(bdms_fbc_result_scheme.getModelId()));
            // calSchemeInfo.setXishu(String.valueOf(bdms_fbc_result_scheme.getExpparam()));
            // calSchemeInfo.setTyphoonDepart(bdms_fbc_result_scheme.getReportDept());
            calSchemeInfo.setState(bdms_fbc_result_scheme.getState());
            if (bdms_fbc_result_scheme.getState()!=null){
                switch (bdms_fbc_result_scheme.getState()){
                    case 0:
                        calSchemeInfo.setStateInfo("新建方案");
                        break;
                    case 1:
                        calSchemeInfo.setStateInfo("计算中");
                        break;
                    case 2:
                        calSchemeInfo.setStateInfo("计算失败");
                        break;
                    case 3:
                        calSchemeInfo.setStateInfo("计算完成");
                        break;
                    default:
                        break;
                }
            }
            calSchemeInfo.setForecastSchemeId(bdms_fbc_result_scheme.getFschemeid());
            calSchemeInfo.setForecastTime(bdms_fbc_result_scheme.getDtmforecast());
            calSchemeInfo.setForecastBeginTime(bdms_fbc_result_scheme.getDtmstart());
            calSchemeInfo.setForecastEndTime(bdms_fbc_result_scheme.getDtmend());
            calSchemeInfo.setDescription(bdms_fbc_result_scheme.getRemark());
            calSchemeInfos.add(calSchemeInfo);
        }

        return calSchemeInfos;

    }
    //GetForecastStationInfos
    @ApiOperation("获取计算方案信息")
    @RequestMapping(value = "GetCalSchemeInfos", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult getForecastStationInfos(@RequestBody GetCalSchemeInfoParam getCalSchemeInfoParam) {
        JsonResult jsonResult = new JsonResult();
        List<CalSchemeInfo> calSchemeInfos = new ArrayList<>();
        List<BDMS_CALCULATESCHEME_M> bdms_calculatescheme_ms = bdms_calculatescheme_mService.selectAllByPid(getCalSchemeInfoParam.getProjectId(),getCalSchemeInfoParam.getCalSchemeId(),getCalSchemeInfoParam.getStartTime()
                ,getCalSchemeInfoParam.getEndTime(),false);
        for (BDMS_CALCULATESCHEME_M bdms_calculatescheme_m:bdms_calculatescheme_ms){
            CalSchemeInfo calSchemeInfo = new CalSchemeInfo();
            calSchemeInfo.setCalSchemeId(bdms_calculatescheme_m.getCschemeid());
            if (bdms_calculatescheme_m.getAliasnm()!=null){
                calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getAliasnm());
            }else {
                calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getCschemenm());
            }
            // calSchemeInfo.setCalTimeSpan(bdms_calculatescheme_m.getCalinterval());
            calSchemeInfo.setForecastTime(bdms_calculatescheme_m.getDtmforecast());
            calSchemeInfo.setOperateTime(bdms_calculatescheme_m.getDtmcalculate());
            calSchemeInfo.setForecastSchemeId(bdms_calculatescheme_m.getFschemeid());
            if (bdms_calculatescheme_m.getState()!=null){
                switch (bdms_calculatescheme_m.getState()){
                    case 0:
                        calSchemeInfo.setStateInfo("新建方案");
                        break;
                    case 1:
                        calSchemeInfo.setStateInfo("计算中");
                        break;
                    case 2:
                        calSchemeInfo.setStateInfo("计算失败");
                        break;
                    case 3:
                        calSchemeInfo.setStateInfo("计算完成");
                        break;
                    default:
                        break;
                }
            }
            calSchemeInfo.setState(bdms_calculatescheme_m.getState());
            calSchemeInfo.setUserId(String.valueOf(bdms_calculatescheme_m.getUserid()));
            calSchemeInfo.setForecastBeginTime(bdms_calculatescheme_m.getDtmstart());
            calSchemeInfo.setForecastEndTime(bdms_calculatescheme_m.getDtmend());
            calSchemeInfo.setDescription(bdms_calculatescheme_m.getRemark());
            calSchemeInfos.add(calSchemeInfo);
        }
//        CalSchemeInfo calSchemeInfo = new CalSchemeInfo();
//        calSchemeInfo.setCalSchemeId(getCalSchemeInfoParam.getCalSchemeId());
//        calSchemeInfo.setForecastSchemeId("23040101");
//            calSchemeInfo.setCalSchemeName("水质测试计算");
//            calSchemeInfo.setCalInterval(60);
//            calSchemeInfo.setForecastTime("2023-05-18 08:00:00");
//            calSchemeInfo.setOperateTime("2023-05-15 10:00:00");
//            calSchemeInfo.setStateInfo("新建方案");
//            calSchemeInfo.setState(0);
//            calSchemeInfo.setUserId("1");
//            calSchemeInfo.setForecastBeginTime("2023-05-15 08:00:00");
//            calSchemeInfo.setForecastEndTime("2023-05-21 08:00:00");
//            calSchemeInfo.setDescription("测试");
//            calSchemeInfos.add(calSchemeInfo);
        jsonResult.setData(calSchemeInfos);
        jsonResult.setSucceeded(true);
        jsonResult.setStatusCode(200);
        return jsonResult;
    }





    public List<Data> getDatas(String startTime, String endTime,String dataType) throws ParseException {
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        List<Data> datas = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = format.parse(startTime.substring(0,19));
        Date endDate = format.parse(endTime.substring(0,19));
        long differenceInMillis = endDate.getTime() - startDate.getTime();
        int hourDifference = (int) (differenceInMillis / (60 * 60 * 1000));
        Random random = new Random();
        double lowerBound;
        double upperBound;
        String formattedValue;
        double result;
        switch(dataType) {
            case "TN（总氮）":
                lowerBound = 0;
                upperBound = 1;
                for (int i=0;i<hourDifference;i++){
                    calendar.setTime(startDate);
                    calendar.add(Calendar.HOUR,+i);
                    Data data = new Data();
                    data.setTM(format.format(calendar.getTime()));
                    formattedValue = decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble()));
                    result = Double.parseDouble(formattedValue);

                    data.setValue(result);
                    datas.add(data);
                }
                break;
            case "氨氮":
                lowerBound = 0;
                upperBound = 1;
                for (int i=0;i<hourDifference;i++){
                    calendar.setTime(startDate);
                    calendar.add(Calendar.HOUR,+i);
                    Data data = new Data();
                    data.setTM(format.format(calendar.getTime()));
                    formattedValue = decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble()));
                    result = Double.parseDouble(formattedValue);
                    data.setValue(result);
                    datas.add(data);
                }
                break;
            case "COD（化学需氧量）":
                lowerBound = 0;
                upperBound = 6;
                for (int i=0;i<hourDifference;i++){
                    calendar.setTime(startDate);
                    calendar.add(Calendar.HOUR,+i);
                    Data data = new Data();
                    data.setTM(format.format(calendar.getTime()));
                    formattedValue = decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble()));
                    result = Double.parseDouble(formattedValue);
                    data.setValue(result);
                    datas.add(data);
                }
                break;
//            case "BOD（生化需氧量）":
//                lowerBound = 0;
//                upperBound = 10;
//                for (int i=0;i<hourDifference;i++){
//                    calendar.setTime(startDate);
//                    calendar.add(Calendar.HOUR,+i);
//                    Data data = new Data();
//                    data.setTM(format.format(calendar.getTime()));
//                    formattedValue = decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble()));
//                    result = Double.parseDouble(formattedValue);
//                    data.setValue(result);
//                    datas.add(data);
//                }
//                break;
            case "总磷":
                lowerBound = 0;
                upperBound = 0.2;
                for (int i=0;i<hourDifference;i++){
                    calendar.setTime(startDate);
                    calendar.add(Calendar.HOUR,+i);
                    Data data = new Data();
                    data.setTM(format.format(calendar.getTime()));
                    formattedValue = decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble()));
                    result = Double.parseDouble(formattedValue);
                    data.setValue(result);
                    datas.add(data);
                }
                break;
            default:
                // Handle other data types here
                break;
        }
        return datas;
    }

    public List<ModelData> getmodelDatas(String starttm,String dtmF,String endtm,String valueModelName,String stationCode,String dataType) throws ParseException {
        List<ModelData> modelDatas = new ArrayList<>();
        String[] dataCodes = {"1101", "1102" };
        String[] dataTypes = {"模拟", "预报"};
        for (int i = 0; i < dataCodes.length; i++) {
            ModelData modelData = new ModelData();
            List<com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data> datas = null;
            if (i==0){
                datas = getDatas(starttm,dtmF,0,valueModelName);
            }else {
                calendar.setTime(format.parse(dtmF));
                calendar.add(Calendar.HOUR,+1);
                datas = getDatas(format.format(calendar.getTime()),endtm,0,valueModelName);
            }

            com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data maxData = datas.stream()
                    .max(Comparator.comparing(data -> Double.parseDouble(data.getValue())))
                    .orElse(null);
            com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data minData = datas.stream()
                    .max(Comparator.comparing(data -> Double.parseDouble(data.getValue())))
                    .orElse(null);

            modelData.setDataCode(dataType);
            modelData.setDataType(dataTypes[i]+valueModelName);
            modelData.setValues(datas);
            modelData.setMaxValue(maxData.getValue());
            modelData.setMaxTm(maxData.getTime());
            modelData.setMinValue(minData.getValue());
            modelData.setMinTm(minData.getTime());
            modelDatas.add(modelData);
        }
        return modelDatas;
    }

    public static com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data dataEstimate(String result1, String dataType){
        com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data data = new com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data();
        Double result = Double.parseDouble(result1);
        switch (dataType){
            case "TN":
                data.setValue(result1);
                if (result <= 0.2) {

                    data.setLevel("I类");
                    data.setStatus(1);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/0.2)));

                } else if (result <= 0.5) {

                    data.setLevel("II类");
                    data.setStatus(2);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/0.5)));

                } else if (result <=1) {

                    data.setLevel("III类");
                    data.setStatus(3);
                    data.setIndex(result);


                } else if (result <= 1.5) {
                    data.setLevel("IV类");
                    data.setStatus(4);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/1.5)));

                } else if (result <= 2.0) {

                    data.setLevel("V类");
                    data.setStatus(4);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/2)));

                }else  {
                    data.setLevel("劣V类");
                    data.setStatus(6);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/2)));
                }
                break;
            case "NH4":
                data.setValue(result1);
                if (result <= 0.15) {

                    data.setLevel("I类");
                    data.setStatus(1);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/0.15)));

                } else if (result <= 0.5) {

                    data.setLevel("II类");
                    data.setStatus(2);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/0.5)));

                } else if (result <=1) {

                    data.setLevel("III类");
                    data.setStatus(3);
                    data.setIndex(result);

                } else if (result <= 1.5) {

                    data.setLevel("IV类");
                    data.setStatus(4);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/1.5)));

                } else if (result <= 2.0) {

                    data.setLevel("V类");
                    data.setStatus(5);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/2)));

                }else  {

                    data.setLevel("劣V类");
                    data.setStatus(6);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/2)));

                }
                break;
            case "cod":
                data.setValue(result1);
                if (result <= 15) {

                    data.setLevel("I类");
                    data.setStatus(1);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/15)));

                } else if (result <= 20) {

                    data.setLevel("III类");
                    data.setStatus(3);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/20)));

                } else if (result <= 30) {

                    data.setLevel("IV类");
                    data.setStatus(4);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/30)));


                } else if (result<=40){

                    data.setLevel("V类");
                    data.setStatus(5);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/40)));

                }else if (result<=40){

                    data.setLevel("劣V类");
                    data.setStatus(6);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/40)));

                }
                break;
            case "TP":
                data.setValue(result1);
                if (result <= 0.02) {

                    data.setLevel("I类");
                    data.setStatus(1);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/0.02)));

                } else if (result <= 0.1) {

                    data.setLevel("II类");
                    data.setStatus(2);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/0.1)));

                } else if (result <= 0.2) {

                    data.setLevel("III类");
                    data.setStatus(3);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/0.2)));


                } else if (result <=0.3) {

                    data.setLevel("IV类");
                    data.setStatus(4);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/0.3)));

                } else if (result<=0.4){

                    data.setLevel("V类");
                    data.setStatus(5);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/0.4)));

                } else{

                    data.setLevel("劣V类");
                    data.setStatus(6);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/0.4)));

                }
                break;
            case "SY":
                data.setValue(result1);
                if (result <= 0.05) {

                    data.setLevel("I类");
                    data.setStatus(1);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/0.05)));

                } else if (result <=0.5) {

                    data.setLevel("IV类");
                    data.setStatus(4);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/0.5)));

                } else if (result<=1){

                    data.setLevel("V类");
                    data.setStatus(5);
                    data.setIndex(result);

                }else {

                    data.setLevel("劣V类");
                    data.setStatus(6);
                    data.setIndex(result);

                }
                break;
            case "CodMn":
                data.setValue(result1);
                if (result <= 2) {

                    data.setLevel("I类");
                    data.setStatus(1);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/2)));

                } else if (result <= 4) {

                    data.setLevel("II类");
                    data.setStatus(2);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/4)));

                } else if (result <= 6) {

                    data.setLevel("III类");
                    data.setStatus(3);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/6)));

                }else if (result <=8) {

                    data.setLevel("IV类");
                    data.setStatus(4);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/8)));

                } else if (result<=10){

                    data.setLevel("V类");
                    data.setStatus(5);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/10)));

                } else{

                    data.setLevel("劣V类");
                    data.setStatus(6);
                    data.setIndex(Double.valueOf(String.format("%.2f", result/10)));

                }
                break;
            default:

                return data;
        }
        System.out.println(data);
        return  data;
    }




    public CalResult getCaldata(String calId,List<String> stationCodes) throws ParseException {
        //  List<CalResult> calResults =new ArrayList<>();


        //查询方案信息
        BDMS_CALCULATESCHEME_M bdms_calculatescheme_m =bdms_calculatescheme_mService.seletcById(calId);
        if (bdms_calculatescheme_m!=null){
            CalResult calResult =new CalResult();
            //  CalResult calResult= new CalResult();
            CalSchemeInfo calSchemeInfo= new CalSchemeInfo();
            calSchemeInfo.setCalSchemeId(bdms_calculatescheme_m.getCschemeid());
            calSchemeInfo.setOperateTime(bdms_calculatescheme_m.getDtmcalculate().substring(0,19));
            if (bdms_calculatescheme_m.getAliasnm()!=null){
                calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getAliasnm());
            }else {
                calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getCschemenm());
            }
            //calSchemeInfo.setCalTimeSpan(bdms_calculatescheme_m.getCalinterval());
            calSchemeInfo.setForecastTime(bdms_calculatescheme_m.getDtmforecast().substring(0,19));
            //calSchemeInfo.setOperateTime(bdms_calculatescheme_m.getDtmstart().substring(0,19));
            if (bdms_calculatescheme_m.getState()!=null){
                switch (bdms_calculatescheme_m.getState()){
                    case 0:
                        calSchemeInfo.setStateInfo("新建方案");
                        break;
                    case 1:
                        calSchemeInfo.setStateInfo("计算中");
                        break;
                    case 2:
                        calSchemeInfo.setStateInfo("计算失败");
                        break;
                    case 3:
                        calSchemeInfo.setStateInfo("计算完成");
                        break;
                    default:
                        break;
                }
            }
            calSchemeInfo.setState(bdms_calculatescheme_m.getState());
            calSchemeInfo.setForecastSchemeId(bdms_calculatescheme_m.getFschemeid());
            calSchemeInfo.setUserId(String.valueOf(bdms_calculatescheme_m.getUserid()));
            calSchemeInfo.setForecastBeginTime(bdms_calculatescheme_m.getDtmstart().substring(0,19));
            calSchemeInfo.setForecastEndTime(bdms_calculatescheme_m.getDtmend().substring(0,19));
            calSchemeInfo.setDescription(bdms_calculatescheme_m.getRemark());
            calResult.setCalSchemeInfo(calSchemeInfo);

            if (bdms_calculatescheme_m.getState()== 3) {
                //根据fstcd获取预报站点信息
                List<BDMS_YB_FORECASTSTATION_B> bdms_yb_forecaststation_bs = bdms_yb_forecaststation_bService.queryById(bdms_calculatescheme_m.getPid(), bdms_calculatescheme_m.getFschemeid());
                if (bdms_calculatescheme_m.getPid()!=2107) {
                    List<CalData> calDatas = new ArrayList<>();
                    for (BDMS_YB_FORECASTSTATION_B bdms_yb_forecaststation_b : bdms_yb_forecaststation_bs) {
                        if (stationCodes.contains(bdms_yb_forecaststation_b.getFstcd())) {
                            CalData calData = new CalData();
                            String stcd = bdms_yb_forecaststation_b.getFstcd();
                            String stnm = bdms_yb_forecaststation_b.getFstnm();
                            calData.setMainHeading(stnm + "(" + stcd + ")水质预报过程图");
                            int grid;
                            if ("true".equals(bdms_calculatescheme_m.getTag())) {
                                grid = Integer.parseInt(bdms_yb_forecaststation_b.getObsnet());
                            } else {
                                grid = Integer.parseInt(bdms_yb_forecaststation_b.getRemark());
                            }
                            calData.setSubHeading("预报时间：" + bdms_calculatescheme_m.getDtmforecast().substring(0, 19) + " 预报根据时间：" + bdms_calculatescheme_m.getDtmstart().substring(0, 19)
                                    + "--" + bdms_calculatescheme_m.getDtmforecast().substring(0, 19));
                            calData.setForecastStationCode(stcd);
                            calData.setStationCode(stnm);
                            List<BDMS_ST_SENSOR_B> bdms_st_sensor_bs = bdms_st_sensor_bService.selectByPid(bdms_calculatescheme_m.getPid());
                            //获取传感器表的所有传感器
                            List<BDMS_ST_SENSOR_B> sensor_bs = bdms_st_sensor_bs.stream().filter(bdmsStSensorB -> bdmsStSensorB.getStcd().equals(stcd)).collect(Collectors.toList());
                            System.out.println(sensor_bs);
                            //根据传感器
                            List<ValueModel> valueModels = new ArrayList<>();
                            for (BDMS_ST_SENSOR_B sensor_b : sensor_bs) {
                                ValueModel valueModel = new ValueModel();
                                valueModel.setUnit("mg/L");
                                valueModel.setDataType(sensor_b.getSensoraliasnm());
                                valueModel.setOrder(Integer.valueOf(sensor_b.getSensoraliasnm().substring(sensor_b.getSensoraliasnm().length() - 2, sensor_b.getSensoraliasnm().length())));
                                List<ModelData> valueDatas = new ArrayList<>();

                                valueModel.setValueName(sensor_b.getSensornm());
                                List<BDMS_SLX_RESULT_M> bdms_slx_result_ms = bdms_slx_result_mService.queryByGrids(calId, grid, Integer.parseInt(sensor_b.getSensoraliasnm()), calSchemeInfo.getForecastBeginTime(), calSchemeInfo.getForecastEndTime());
//                        //根据dttp获取数据
//                        Map<String, List<BDMS_SLX_RESULT_M>> groupedByAge = bdms_slx_result_ms.stream()
//                                .collect(Collectors.groupingBy(person -> {
//                                    String ageString = String.valueOf(person.getDttp());
//                                    return ageString.substring(ageString.length()-2,ageString.length());
//                                }));
                                Map<Boolean, List<BDMS_SLX_RESULT_M>> groupedByTime = bdms_slx_result_ms.stream()
                                        .collect(Collectors.partitioningBy(person -> {
                                            String ageString = String.valueOf(person.getDttm());
                                            try {
                                                return format.parse(ageString).after(format.parse(bdms_calculatescheme_m.getDtmforecast().substring(0, 19)));
                                            } catch (ParseException e) {
                                                throw new RuntimeException(e);
                                            }
                                        }));


                                groupedByTime.forEach((age, values) -> {
                                    ModelData modelData = new ModelData();
                                    if (!age) {
                                        modelData.setDataType("模拟" + sensor_b.getSensornm());
                                    } else {
                                        modelData.setDataType("预报" + sensor_b.getSensornm());
                                    }
                                    modelData.setDataCode(sensor_b.getSensoraliasnm());


                                    List<com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data> dataList = new ArrayList<>();
                                    for (BDMS_SLX_RESULT_M bdms_slx_result_m : values) {
//                               ); String str = String.valueOf(Double.parseDouble(bdms_slx_result_m.getDatavalues())/100000);
//                                System.out.println("long"+str
                                        double vaule = (Double.parseDouble(bdms_slx_result_m.getDatavalues()) / 100000L);
                                        // System.out.println("value"+vaule);
                                        DecimalFormat decimalFormat = new DecimalFormat("#.######");
                                        String formattedValue = decimalFormat.format(vaule);
                                        //System.out.println(formattedValue+"ss"+Double.valueOf(formattedValue));
                                        com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data data = dataEstimate(formattedValue, sensor_b.getSensornm());
                                        data.setTime(bdms_slx_result_m.getDttm().substring(0, 19));
                                        dataList.add(data);
                                    }
                                    if (!dataList.isEmpty()) {
                                        modelData.setValues(dataList);
                                        com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data maxData = dataList.stream()
                                                .max(Comparator.comparing(data -> Double.parseDouble(data.getValue())))
                                                .orElse(null);
                                        com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data minData = dataList.stream()
                                                .min(Comparator.comparing(data -> Double.parseDouble(data.getValue())))
                                                .orElse(null);
                                        modelData.setMaxValue(maxData.getValue());
                                        modelData.setMaxTm(maxData.getTime());

                                        modelData.setMinValue(minData.getValue());
                                        modelData.setMinTm(minData.getTime());

                                    }


                                    valueDatas.add(modelData);
                                });


                                valueModel.setValueDatas(valueDatas);
                                valueModels.add(valueModel);
                            }
                            valueModels.sort(Comparator.comparing(ValueModel::getOrder));
                            calData.setCalResults(valueModels);
                            calDatas.add(calData);
                        }

                    }
                    calResult.setCalResult(calDatas);
                }
            }
            return calResult;
        }
        return null;
    }




    //模拟数据

    @ApiOperation("获取计算结果")
    @RequestMapping(value = "GetCalResultByStations", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult getCalResult(@RequestBody JSONObject jsonObject) throws ParseException {
        //String calSchemeIds= jsonObject.getString("calSchemeIds");
        List<String> calSchemeIds= jsonObject.getList("calSchemeIds",String.class);
        List<String> forecastStationCodes= jsonObject.getList("forecastStationCodes",String.class);
        boolean flag =true;
        if (jsonObject.getBoolean("flag")!=null){
            flag =jsonObject.getBoolean("flag");
        }

        List<CalResult> calResults = new ArrayList<>();
        //if (flag){
        for (String cal : calSchemeIds){
            CalResult calResult =  getCaldata(cal,forecastStationCodes);
            if (calResult!=null) {
                calResults.add(calResult);
            }
        }
//        }else {
//            calResults =getCal(230401,calSchemeIds,forecastStationCodes);
//        }


        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(calResults);
        jsonResult.setSucceeded(true);
        jsonResult.setStatusCode(200);
        return jsonResult;
    }
    //预报计算成果入库
    @ApiOperation("预报计算成果入库")
    @RequestMapping(value = "SaveCalSchemeInfo", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult saveCalSchemeInfo(@RequestBody JSONObject jsonObject) {
        String calSchemeId= jsonObject.getString("calSchemeId");
        String description= jsonObject.getString("description");
        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(calSchemeId+"方案已入库");
        jsonResult.setSucceeded(true);
        jsonResult.setStatusCode(200);
        return jsonResult;
    }



    //public List<Sev>

    //单因子单因子水质评价
    public List<com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data> getDatas(String startTime, String endTime, int b, String dataType) throws ParseException {
        List<com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data> datas = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = format.parse(startTime);
        Date endDate = format.parse(endTime);
        calendar.setTime(endDate);
        calendar.add(Calendar.HOUR,+1);
        endDate =calendar.getTime();
        Random random = new Random();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);


        while (calendar.getTime().before(endDate)) {
            String tm = format.format(calendar.getTime());
            com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data data = new com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data();
            data.setTime(tm);
            DecimalFormat decimalFormat = new DecimalFormat("#.##");
            double lowerBound = 0; // Lower bound of the random number
            double upperBound = 0;
            double result =0;
            String formattedValue;
            switch(dataType) {
                case "TN":
                    lowerBound = 0;
                    upperBound = 1;
                    formattedValue = decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble()));
                    result = Double.parseDouble(formattedValue);
                    if (result <= 0.2) {
                        data.setStatus(1);
                        data.setIndex(Double.valueOf(decimalFormat.format(result/0.2)));
                        data.setLevel("I类");
                    } else if (result <= 0.5) {
                        data.setStatus(2);
                        data.setIndex(Double.valueOf(decimalFormat.format(result/0.5)));
                        data.setLevel("II类");
                    } else if (result <=1) {
                        data.setStatus(3);
                        data.setIndex(Double.valueOf(decimalFormat.format(result)));
                        data.setLevel("III类");
                    } else if (result <= 1.5) {
                        data.setStatus(4);
                        data.setIndex(Double.valueOf(decimalFormat.format(result/1.5)));
                        data.setLevel("IV类");
                    } else if (result <= 2.0) {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/2.0)));
                        data.setStatus(5);
                        data.setLevel("V类");
                    }else  {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/2.0)));
                        data.setStatus(6);
                        data.setLevel("劣V类");
                    }
                    break;
                case "NH4":
                    lowerBound = 0;
                    upperBound = 1;
                    formattedValue=   decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble()));
                    result = Double.parseDouble(formattedValue);
                    if (result <= 0.15) {
                        data.setStatus(1);
                        data.setIndex(Double.valueOf(decimalFormat.format(result/0.15)));
                        data.setLevel("I类");
                    } else if (result <= 0.5) {
                        data.setStatus(2);
                        data.setIndex(Double.valueOf(decimalFormat.format(result/0.5)));
                        data.setLevel("II类");
                    } else if (result <=1) {
                        data.setStatus(3);
                        data.setIndex(Double.valueOf(decimalFormat.format(result)));
                        data.setLevel("III类");
                    } else if (result <= 1.5) {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/1.5)));
                        data.setStatus(4);
                        data.setLevel("IV类");
                    } else if (result <= 2.0) {
                        data.setStatus(5);
                        data.setIndex(Double.valueOf(decimalFormat.format(result/2.0)));
                        data.setLevel("V类");
                    }else  {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/2.0)));
                        data.setStatus(6);
                        data.setLevel("劣V类");
                    }
                    break;
                case "cod":
                    lowerBound = 0;
                    upperBound = 40;
                    formattedValue=   decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble()));
                    result = Double.parseDouble(formattedValue);
                    // Adjust the interval calculation for Type B data
                    if (result <= 15) {
                        data.setStatus(1);
                        data.setIndex(Double.valueOf(decimalFormat.format(result/15.0)));
                        data.setLevel("I类");
                    } else if (result <= 20) {
                        data.setStatus(3);
                        data.setIndex(Double.valueOf(decimalFormat.format(result/20.0)));
                        data.setLevel("III类");
                    } else if (result <= 30) {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/30.0)));
                        data.setStatus(4);
                        data.setLevel("IV类");
                    } else if (result<=40){
                        data.setIndex(Double.valueOf(decimalFormat.format(result/40.0)));
                        data.setStatus(5);
                        data.setLevel("V类");
                    }else  {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/40.0)));
                        data.setStatus(6);
                        data.setLevel("劣V类");
                    }
                    break;

                case "CodMn":
                    lowerBound = 0;
                    upperBound = 6;
                    formattedValue=   decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble()));
                    result = Double.parseDouble(formattedValue);
                    // Adjust the interval calculation for Type B data
                    if (result <= 2) {

                        data.setLevel("I类");
                        data.setStatus(1);
                        data.setIndex(Double.valueOf(String.format("%.2f", result/2)));

                    } else if (result <= 4) {

                        data.setLevel("II类");
                        data.setStatus(2);
                        data.setIndex(Double.valueOf(String.format("%.2f", result/4)));

                    } else if (result <= 6) {

                        data.setLevel("III类");
                        data.setStatus(3);
                        data.setIndex(Double.valueOf(String.format("%.2f", result/6)));

                    }else if (result <=8) {

                        data.setLevel("IV类");
                        data.setStatus(4);
                        data.setIndex(Double.valueOf(String.format("%.2f", result/8)));

                    } else if (result<=10){

                        data.setLevel("V类");
                        data.setStatus(5);
                        data.setIndex(Double.valueOf(String.format("%.2f", result/10)));

                    }else  {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/10)));
                        data.setStatus(6);
                        data.setLevel("劣V类");
                    }
                    break;
                case "SY":
                    lowerBound = 0;
                    upperBound = 2;
                    formattedValue=   decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble()));
                    result = Double.parseDouble(formattedValue);
                    // Adjust the interval calculation for Type B data
                    if (result <= 0.05) {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/0.05)));
                        data.setStatus(1);
                        data.setLevel("I类");
                    }
                    else if (result <=0.5) {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/0.5)));
                        data.setStatus(4);
                        data.setLevel("IV类");
                    } else if (result<=1){
                        data.setIndex(Double.valueOf(decimalFormat.format(result)));
                        data.setStatus(5);
                        data.setLevel("V类");
                    }else  {
                        data.setIndex(Double.valueOf(decimalFormat.format(result)));
                        data.setStatus(6);
                        data.setLevel("劣V类");
                    }
                    break;
                case "TP":
                    lowerBound = 0;
                    upperBound = 0.2;
                    formattedValue=   decimalFormat.format((lowerBound + (upperBound - lowerBound) * random.nextDouble()));
                    result = Double.parseDouble(formattedValue);
                    // Adjust the interval calculation for Type B data
                    if (result <= 0.02) {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/0.02)));
                        data.setStatus(1);
                        data.setLevel("I类");
                    } else if (result <= 0.1) {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/0.1)));
                        data.setStatus(2);
                        data.setLevel("II类");
                    } else if (result <= 0.2) {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/0.2)));
                        data.setStatus(3);
                        data.setLevel("III类");
                    } else if (result <=0.3) {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/0.3)));
                        data.setStatus(4);
                        data.setLevel("IV类");
                    } else if (result<=0.4){
                        data.setIndex(Double.valueOf(decimalFormat.format(result/0.4)));
                        data.setStatus(5);
                        data.setLevel("V类");
                    }else  {
                        data.setIndex(Double.valueOf(decimalFormat.format(result/0.4)));
                        data.setStatus(6);
                        data.setLevel("劣V类");
                    }
                    break;
                default:
                    // Handle other data types here
                    break;
            }
            data.setValue(String.valueOf(result));
            datas.add(data);
            calendar.add(Calendar.HOUR, 1);
        }
        return datas;
    }

    @ApiOperation("水质评价")
    @RequestMapping(value = "WateQualityEvaluation", headers = "Accept=application/json", method = RequestMethod.GET)
    public JsonResult WateQualityEvaluation(@RequestParam List<String> stationCodes,@RequestParam String startTime,
                                            @RequestParam String endTime,@RequestParam(required = false) boolean flag) throws ParseException {
        JsonResult jsonResult = new JsonResult();
        List<SingleEvaluationResult> singleEvaluationResults= new ArrayList<>();
        flag =true;
        if (flag){
            //根据站点集合获取站点数据
            List<WQ_AWQMD_D> wq_awqmd_ds = wq_awqmd_dService.queryAllByStcds(stationCodes,startTime,endTime);
            List<BDMS_ST_SENSOR_B> bdms_st_sensor_bs = bdms_st_sensor_bService.selectBySTCDS(stationCodes);
            //根据站点集合的站点分组
            Map<String, List<WQ_AWQMD_D>> groupedData = wq_awqmd_ds.stream()
                    .collect(Collectors.groupingBy(WQ_AWQMD_D::getStcd));
            // 打印每个站点的数据
            for (Map.Entry<String, List<WQ_AWQMD_D>> entry : groupedData.entrySet()) {
                SingleEvaluationResult singleEvaluationResult = new SingleEvaluationResult();
                singleEvaluationResult.setStationCode(entry.getKey());
                //获取传感器表的所有传感器
                List<BDMS_ST_SENSOR_B> sensor_bs = bdms_st_sensor_bs.stream().filter(bdmsStSensorB -> bdmsStSensorB.getStcd().equals(entry.getKey())).collect(Collectors.toList());
                //根据传感器
                List<Sev> sevs = new ArrayList<>();
                for (BDMS_ST_SENSOR_B bdms_st_sensor_b : sensor_bs) {
                    System.out.println(bdms_st_sensor_b.getSensortps());
                    if ("SY".equals(bdms_st_sensor_b.getSensortps())){
                        continue;
                    }
                    singleEvaluationResult.setStationName(bdms_st_sensor_b.getStnm());
                    Sev sev = new Sev();
                    sev.setDataCode(entry.getKey() );
                    sev.setWaterQualityName(bdms_st_sensor_b.getSensornm());
                  //  sev.setOrder(Integer.parseInt(bdms_st_sensor_b.getSensoraliasnm().substring(bdms_st_sensor_b.getSensoraliasnm().length() - 2, bdms_st_sensor_b.getSensoraliasnm().length())));
                    sev.setUnit("mg/L");
                    List<com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data> dataList = new ArrayList<>();
                    for (WQ_AWQMD_D wq_awqmd_d : entry.getValue()) {

                        com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data data;
                        switch (bdms_st_sensor_b.getSensortps()) {
                            case "CodMn":
                                sev.setDataCode(entry.getKey() + "1106");
                                sev.setWaterQualityName("CodMn");
                                //sev.setOrder(Integer.parseInt(bdms_st_sensor_b.getSensoraliasnm().substring(bdms_st_sensor_b.getSensoraliasnm().length() - 2, bdms_st_sensor_b.getSensoraliasnm().length())));
                                //化学需氧量
                                if (wq_awqmd_d.getCodmn()!=null){
                                    data =dataEstimate(String.format("%.2f", wq_awqmd_d.getCodmn()), bdms_st_sensor_b.getSensortps());
                                    data.setTime(wq_awqmd_d.getSpt());
                                    dataList.add(data);
                                }
                                break;
                            case "TN":
                                System.out.println("wq:"+wq_awqmd_d);
                                // 总氮
                                if (wq_awqmd_d.getTn()!=null){
                                    System.out.println("tn"+wq_awqmd_d.getTn());
                                    data =dataEstimate((String.format("%.2f", wq_awqmd_d.getTn())), bdms_st_sensor_b.getSensortps());
                                    System.out.println(data);
                                    data.setTime(wq_awqmd_d.getSpt());
                                    dataList.add(data);
                                }
                                break;
                            case "TP":
                                // 总磷
                                if (wq_awqmd_d.getTp()!=null){
                                    data = dataEstimate((String.format("%.2f", wq_awqmd_d.getTp())), bdms_st_sensor_b.getSensortps());
                                    data.setTime(wq_awqmd_d.getSpt());
                                    dataList.add(data);
                                }
                                break;
                            case "NH4":
                                // 氨氮
                                if (wq_awqmd_d.getNh3n()!=null){
                                    data = dataEstimate((String.format("%.2f", wq_awqmd_d.getNh3n())), bdms_st_sensor_b.getSensortps());
                                    data.setTime(wq_awqmd_d.getSpt());
                                    dataList.add(data);
                                }
                                break;
                            default:
                                break;
                        }

                    }
                    dataList.sort(Comparator.comparing(com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data::getTime));
                    System.out.println(dataList);
                    sev.setDataValues(dataList);
                    sevs.add(sev);
                }
                singleEvaluationResult.setSingleEvaluationResults(sevs);
                Map<String, Double> sumMap = new HashMap<>();
                Map<String, Integer> countMap = new HashMap<>();
                for (Sev sev : sevs) {
                    if (sev.getDataValues().size() > 0) {
                        for (com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data data : sev.getDataValues()) {
                            if (data.getIndex()!=null) {
                                String time = data.getTime();
                                Double wqgp = data.getIndex();
                                if (sumMap.containsKey(time)) {
                                    sumMap.put(time, sumMap.get(time) + wqgp);
                                    countMap.put(time, countMap.get(time) + 1);
                                } else {
                                    sumMap.put(time, wqgp);
                                    countMap.put(time, 1);
                                }
                            }
                        }
                    }
                }
                Map<String, Double> averageMap = new HashMap<>();
                for (String time : sumMap.keySet()) {
                    Double sum = sumMap.get(time);
                    Integer count = countMap.get(time);
                    Double average = sum / count;
                    averageMap.put(time, average);
                }
                // Create a list to store MultiData objects
                List<MultiData> multiDataList = new ArrayList<>();
                // Iterate through the averageMap to create MultiData objects
                for (String time : averageMap.keySet()) {
                    Double average = averageMap.get(time);
                    // Create a new MultiData object
                    MultiData multiData = new MultiData();
                    // Assign values to the attributes
                    multiData.setTime(time);
                    multiData.setP(Double.valueOf(String.format("%.2f",average)));
                    // 根据 p 值赋值 condition 字段
                    if (average <= 0.20) {
                        multiData.setCondition("好");
                    } else if (average <= 0.40) {
                        multiData.setCondition("较好");
                    } else if (average <= 0.70) {
                        multiData.setCondition("轻度污染");
                    } else if (average <= 1.00) {
                        multiData.setCondition("中度污染");
                    } else if (average <= 2.00) {
                        multiData.setCondition("重污染");
                    } else {
                        multiData.setCondition("严重污染");
                    }
                    // Add the MultiData object to the list
                    multiDataList.add(multiData);
                    multiDataList.sort(Comparator.comparing(MultiData::getTime));
                }
                singleEvaluationResult.setMultiEvaluationResults(multiDataList);
                singleEvaluationResults.add(singleEvaluationResult);
            }
        }else {
            for (String stationCode : stationCodes) {
                SingleEvaluationResult singleEvaluationResult = new SingleEvaluationResult();
                singleEvaluationResult.setStationCode(stationCode);
                if ("80060002".equals(stationCode)) {
                    singleEvaluationResult.setStationName("邓楼泵站");
                }
                if ("80060003".equals(stationCode)) {
                    singleEvaluationResult.setStationName("八里湾泵站");
                }

                List<Sev> sevs = new ArrayList<>();
                String[] dataCodes = {"1101", "1102", "1105","1106"};
                String[] valueNames = {"TN", "TP",  "NH4","CodMn"};
                for (int i = 0; i < dataCodes.length; i++) {
                    Sev sev = new Sev();
                    sev.setDataCode(dataCodes[i]);
                    sev.setOrder(i + 1);
                    sev.setWaterQualityName(valueNames[i]);
                    sev.setUnit("mg/L");
                    List<com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data> datas = getDatas(startTime, endTime, 0, valueNames[i]);
                    datas.sort(Comparator.comparing(com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data::getTime));
                    sev.setDataValues(datas);
                    sevs.add(sev);
                }

                singleEvaluationResult.setSingleEvaluationResults(sevs);
                Map<String, Double> sumMap = new HashMap<>();
                Map<String, Integer> countMap = new HashMap<>();
                for (Sev sev : sevs) {
                    for (com.jhhc.WaterQuality.Calculate.Forecast.entity.result.Data data : sev.getDataValues()) {
                        String time = data.getTime();
                        Double wqgp = data.getIndex();
                        if (sumMap.containsKey(time)) {
                            sumMap.put(time, sumMap.get(time) + wqgp);
                            countMap.put(time, countMap.get(time) + 1);
                        } else {
                            sumMap.put(time, wqgp);
                            countMap.put(time, 1);
                        }
                    }
                }
                Map<String, Double> averageMap = new HashMap<>();
                for (String time : sumMap.keySet()) {
                    Double sum = sumMap.get(time);
                    Integer count = countMap.get(time);
                    Double average = sum / count;
                    averageMap.put(time, average);
                }
                // Create a list to store MultiData objects
                List<MultiData> multiDataList = new ArrayList<>();
                // Iterate through the averageMap to create MultiData objects
                for (String time : averageMap.keySet()) {
                    Double average = averageMap.get(time);
                    // Create a new MultiData object
                    MultiData multiData = new MultiData();
                    // Assign values to the attributes
                    multiData.setTime(time);
                    multiData.setP(Double.valueOf(String.format("%.2f",average)));
                    // 根据 p 值赋值 condition 字段
                    if (average <= 0.20) {
                        multiData.setCondition("好");
                    } else if (average <= 0.40) {
                        multiData.setCondition("较好");
                    } else if (average <= 0.70) {
                        multiData.setCondition("轻度污染");
                    } else if (average <= 1.00) {
                        multiData.setCondition("中度污染");
                    } else if (average <= 2.00) {
                        multiData.setCondition("重污染");
                    } else {
                        multiData.setCondition("严重污染");
                    }
                    // Add the MultiData object to the list
                    multiDataList.add(multiData);
                    multiDataList.sort(Comparator.comparing(MultiData::getTime));
                }
                singleEvaluationResult.setMultiEvaluationResults(multiDataList);
                singleEvaluationResults.add(singleEvaluationResult);
            }

        }
        jsonResult.setData(singleEvaluationResults);
        jsonResult.setSucceeded(true);
        jsonResult.setStatusCode(200);
        return jsonResult;
    }





    @ApiOperation("获取预报场的计算结果")
    @RequestMapping(value = "GetCalResultsByDomain", headers = "Accept=application/json", method = RequestMethod.GET)
    public JsonResult getCalResultsByDomain(@RequestParam String calSchemeId,
                                            @RequestParam(required = false) String startTime,
                                            @RequestParam(required = false) String endTime,
                                            @RequestParam Integer dttp,
                                            @RequestParam(defaultValue = "true") boolean isData) {
        JsonResult jsonResult = new JsonResult();

        //初始时间
        long start = System.currentTimeMillis();
        Result result = bdmsWqResultMService.
                getCalResultsByDomain(calSchemeId, startTime,endTime, dttp,isData);
        if (result != null) {
            jsonResult.setData(result);
        }
        jsonResult.setStatusCode(200);
        jsonResult.setSucceeded(true);
        //结束时间
        long end = System.currentTimeMillis();
        //打印
        System.out.println("程序运行时间：" + (end - start) + "ms");
        return jsonResult;
    }
}
